package com.lk.security.authentication;

import com.alibaba.fastjson.JSON;
import com.lk.base.result.Result;
import com.lk.security.properties.LoginResponseType;
import com.lk.security.properties.SecurityProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @program: lk-security-parent
 * @description: 自定义认证成功处理器 1. 决定 响应json还是跳转页面，或者认证成功进行其他处理
 * @author: Aspirin
 * @create: 2020-05-26 20:10
 * @remarks: 如果要重定向到上次请求的地址上，不能implements AuthenticationSuccessHandler 而要extends
 *     SavedRequestAwareAuthenticationSuccessHandler
 */
@Component("customAuthenticationSuccessHandler")
public class CustomAuthenticationSuccessHandler
    extends SavedRequestAwareAuthenticationSuccessHandler {
  // public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

  private static final Logger logger =
      LoggerFactory.getLogger(CustomAuthenticationSuccessHandler.class);

  @Autowired SecurityProperties securityProperties;

  /** required = false这样容器中可以不需要实例 */
  @Autowired(required = false)
  AuthenticationSuccessListener authenticationSuccessListener;

  @Override
  public void onAuthenticationSuccess(
      HttpServletRequest request, HttpServletResponse response, Authentication authentication)
      throws IOException, ServletException {
    if (authenticationSuccessListener != null) {
      // 当认证成功后，调用此监听，进行后续处理，比如用户权限菜单
      authenticationSuccessListener.successListener(request, response, authentication);
    }
    if (LoginResponseType.JSON.equals(securityProperties.getAuthentication().getLoginType())) {
      // 认证成功后，响应JSON字符串
      Result result = Result.ok("认证成功！");
      response.setContentType("application/json;charset=UTF-8");
      response.getWriter().write(result.toJsonString());
    } else {
      // 重定向 默认重定向到上次请求的地址上，引发跳转到认证页面的地址
      logger.info("authentication:{}", JSON.toJSONString(authentication));
      super.onAuthenticationSuccess(request, response, authentication);
    }
  }
}
